import { defineStore } from 'pinia'
// 静态路由
import router, { DynamicRoutes } from '@/router/index'
// 后端路由
import { setDefaultRoute } from '@/router/router-recursion'
import view from '@/components/view/view.vue'
import { removeToken } from '@/utils'

function typeOf(obj: any): any {
  const toString: any = Object.prototype.toString
  const map: any = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object',
  }
  return map[toString.call(obj)]
}
function clone(data: any): any {
  const t = typeOf(data)
  let o: any

  if (t === 'array') {
    o = []
  } else if (t === 'object') {
    o = {}
  } else {
    return data
  }

  if (t === 'array') {
    for (let i = 0; i < data.length; i++) {
      o.push(clone(data[i]))
    }
  } else if (t === 'object') {
    for (const i in data) {
      o[i] = clone(data[i])
    }
  }
  return o
}

export const loadView = (view: String) => {
  // 路由懒加载
  return view
}

//递归处理后端数据
function filterAsyncRouter(asyncRouterMap: Array<any>) {
  return asyncRouterMap.filter((route: any) => {
    if (route.children) {
      route.component = view
    } else {
      route.component = loadView(route.component)
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

export const useLoginStore = defineStore('login', {
  persist: {
    key: 'login', // 默认值 store.$id
    storage: sessionStorage,
    paths: undefined,
    beforeRestore: (ctx) => {
      console.log(`即将恢复 '${ctx.store.$id}'`)
    },
  },
  state: () => {
    return {
      /** 所有路由 */
      permissionList: [],
      /* 面包屑导航列表 */
      crumbList: [],
      /** 导航菜单 */
      sidebarMenu: [],
      currentMenu: 'home',
      isSidebarNavCollapse: false,
    }
  },
  getters: {
    getCrumbList(): any[] {
      return this.crumbList
    },
    getMenu(): IRouteInfo[] {
      return this.sidebarMenu
    },
    getCurrentMenu(): string {
      return this.currentMenu
    },
    getIsSidebarNavCollapse(): boolean {
      return this.isSidebarNavCollapse
    },
  },
  actions: {
    /* 面包屑导航列表 */
    SET_CRUMB_LIST(list: []) {
      this.crumbList = list
    },
    /* 左边导航栏列表 */
    SET_MENU(menu: []) {
      this.sidebarMenu = menu
    },
    /* 完整的路由表 */
    SET_PERMISSION(routes: []) {
      this.permissionList = routes
    },
    /* 当前选中的导航 */
    SET_CURRENT_MENU(currentMenu: string) {
      this.currentMenu = currentMenu
    },

    async FETCH_PERMISSION(permissionList: IRouteInfo[]) {
      /* 处理需要动态的路由 */
      const routes: IRouteInfo[] = filterAsyncRouter(permissionList)
      /* 不需要动态的路由（深拷贝） */
      const MainContainer = clone(DynamicRoutes).find(
        (v: IRouteInfo) => v.path === '',
      )
      let children: IRouteInfo[] = []
      children = MainContainer.children
      /* 将两种路由结合生成左边的导航栏 */
      children = children.concat(routes)
      this.SET_MENU(children as [])
      MainContainer.children = children
      setDefaultRoute([MainContainer])
      /* 初始路由 */
      const initialRoutes = router.options.routes
      router.addRoute(MainContainer)
      /* 完整的路由表 */
      this.SET_PERMISSION([...initialRoutes, ...DynamicRoutes] as [])
    },
    /* 清空动态路由和菜单栏 */
    async CLEAR_ALL_ROUTES() {
      this.SET_MENU([])
      this.SET_PERMISSION([])
      removeToken()
      // localStorage.clear()
      // sessionStorage.clear()
    },
  },
})
